import { PageContainer } from '@ant-design/pro-layout';
import { Drawer, message, Modal, Popconfirm, Upload} from 'antd';
import ProTable, { ActionType } from '@ant-design/pro-table';
import React, { useState} from 'react';
import type { ProColumns } from '@ant-design/pro-table';
import { useRef } from 'react';
import { Button } from 'antd';
import {findServiceDealer,findProviderList,addProvider,editProvider,addServiceDealer,pDeleteById,unboundDealerAndServiceProvider} from './service';
import ProForm, { DrawerForm, ModalForm, ProFormText } from '@ant-design/pro-form';
import { PlusOutlined } from '@ant-design/icons';
import request from '@/utils/request';
import { newUUID } from '@/utils/utils';
const { confirm } = Modal;

export default () => {
  const [currentRecord,setCurrentRecord] = useState<any>({});
  const [serviceInfo,setServiceInfo] = useState<any>({});
  const [showDetail, setShowDetail] = useState(false);
  const actionRef = useRef<ActionType>();
  const [services,setServices] = useState<any>([]);
  const [dealerService,setDealerService] = useState<any>([]);
  const [showService, setShowService] = useState(false);
  const [modalVisible,setModalVisible] = useState(false);
  const [fileList1,setFileList1] = useState<any>([]);
  const [fileList2,setFileList2] = useState<any>([]);
  const [shipId,setShipId] = useState('');

  const initFile = async(flag:string,record:any)=>{
    var param:any={"shipId":flag=="1"?record.serviceLicenseShipId:record.serviceAccountShipId};
    if(!param.shipId){
      return
    }
    var data =  request('/xwyl/attachment/attachListData',{
      method: 'POST',
      requestType:'form',
      data: {
        ...param,
      },
    });
    var val =await data;
    if(val.errorCode="200"){
      val.data.forEach((element:any) => {
        element.uid=element.id;
        element.name=element.attName;
        element.url=element.attPath;
        element.status='done';
      });
      if(flag=="1"){
        setFileList1(val.data)
      }else{
        setFileList2(val.data)
      }
    }
  }
  const sColumn: ProColumns[] = [
    {
      title:'名称',
      dataIndex: 'serviceName',
    },
    {
      title:'联系人',
      dataIndex: 'serviceContact',
    },
    {
      title:'电话',
      dataIndex: 'servicePhone',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType:'date',
      hideInSearch:true,
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      valueType:'date',
      hideInSearch:true,
    },
    {
      title: "操作",
      valueType: 'option',
      width:150,
      render: (text, record:any,_, action) => [
        <a hidden={showDetail} onClick={()=>{
          setServiceInfo(record)
      
          //获取下图片
          if(record.serviceLicenseShipId){
            setShipId(record.serviceLicenseShipId.replace("_1",""))
          }else if(record.serviceAccountShipId){
            setShipId(record.serviceAccountShipId.replace("_2",""))
          }else{
            const uuid = newUUID()
            record.serviceLicenseShipId = uuid+"_1"
            record.serviceAccountShipId = uuid+"_1"
            setShipId(uuid)
          }
          initFile("1",record)
          initFile("2",record)
          setModalVisible(true)
        }}>修改</a>,
        <Popconfirm title='确定要删除吗?' key='delete' onConfirm={async() => {
          var val = await pDeleteById({id:record.id})
          if (val.errorCode === '200') {
            refershService()
          } else {
            message.error('绑定失败');
          }
        }}><a hidden={showDetail}>删除</a></Popconfirm>,
        <a key="select" hidden={!showDetail} onClick={async()=>{
          var val = await addServiceDealer({serviceId:record.id,dealerId:currentRecord.dealerId,isActive:'0'})
          if (val.errorCode === '200') {
            initDetail(currentRecord)
            setShowService(false)
          } else {
            message.error('删除失败');
          }
        }
        }>选择</a>
      ]
    }
  ]

  const columnService: ProColumns[] = [
    {
      title:'名称',
      dataIndex: 'serviceName',
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      valueType:'date',
      hideInSearch:true,
    },
    {
      title: '当前服务商',
      dataIndex: 'isActive',
      width:100,
      valueType:'select',
      valueEnum:{
        "1":{text:'是'},
        '0':{text:'否'}
      },
      hideInSearch:true,
    },
    {
      title: "操作",
      valueType: 'option',
      width:260,
      render: (text, record:any,_, action) => [
       <a
       key="detail2" hidden={record.isActive=="1"}
       onClick={async() => {
          var val = await addServiceDealer({serviceId:record.serviceId,dealerId:currentRecord.dealerId,isActive:'1'})
          if (val.errorCode === '200') {
            initDetail(currentRecord)
          } else {
            message.error('绑定失败');
          }
       }}
     >
       设定当前服务商
     </a>,
     <Popconfirm title='确定要删除吗?' key='delete' onConfirm={async() => {
       var val = await unboundDealerAndServiceProvider({serviceId:record.serviceId,dealerId:currentRecord.dealerId})
       if (val.errorCode === '200') {
        initDetail(currentRecord)
      } else {
        message.error('删除失败');
      }
     }}><a hidden={record.flag=="1"}>删除</a></Popconfirm>

    ]
    }
  ]
  //表头信息以及表值设置
  const columns: ProColumns[] = [
    {
      title:'客户代码',
      dataIndex: 'dealerCode',
    },
    
    {
      title:'客户名称',
      dataIndex: 'dealerName',
    },
    {
      title:'地区',
      dataIndex: 'area',
      hideInSearch:true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      hideInSearch:true,
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      hideInSearch:true,
    },
    {
      title: '当前服务商',
      dataIndex: 'serviceName',
      hideInSearch:true,
    }
    ,{
      title: '服务商',
      dataIndex: 'haveService',
      width: 100,
      valueType:'select',
      hideInTable:true,
      valueEnum:{
        "true":{text:'有'},
        'false':{text:'无'}
      },
    },
    {
      title: "操作",
      valueType: 'option',
      render: (text, record:any,_, action) => [
        <a
        key="detail"
        onClick={async() => {
          initDetail(record)
        }}
      >
        详情
      </a>
    ]
    }
  ];

  const initDetail=async(record:any)=>{
    var param = {dealerId:record.dealerId}

    var val = await findServiceDealer(param)
    if (val.errorCode === '200') {
      setShowDetail(true);
      setCurrentRecord(record)
      setDealerService(val.data)
    } else {
      message.error('获取失败');
    }
  }

  const uploadButton = (list:any)=>(
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>点击上传</div>
    </div>
  );


  const uploadProps = {
    name: 'file',
    accept:'image/*',
    action: '/xwyl/attachment/uploadAttach',
    headers: {
      authorization: 'authorization-text',
    },
    beforeUpload:(file: any, FileList: any[])=>{
      var flag =  file.type.indexOf('image/')>=0;
      if(!flag){
         message.error('请上传图片格式或pdf格式')
      }
      return flag;
    }
  };

  const refershService=async()=>{
    var val = await findProviderList({current:1,pageSize:100})
    if (val.errorCode === '200') {
      setServices(val.data)
      setShowService(true)
    } else {
      message.error('获取失败');
    }
  }
  
  return (
    <PageContainer>
    <ProTable
      headerTitle='客户列表'
      pagination={{
        pageSizeOptions:['20', '100', '500']
      }}
      actionRef={actionRef}
      scroll={{x:1200}}
      request ={async(params, sorter, filter) => {
        params.isActive='1'
        return findServiceDealer({ ...params, sorter, filter })
      }}
      columns={columns}
      rowKey="dealerId"
      search={{span:6}}
      toolBarRender={()=>[
        <Button type='primary' key='primary' onClick={async() => {
          refershService()
        }}>服务商</Button>
      ]}
      toolbar={{settings:[]}}
      />
      <Drawer style={{zIndex:90}} title='详情' width={1200} onClose={()=>setShowDetail(false)} visible={showDetail} destroyOnClose={true} forceRender={true}>
          <ProTable pagination={false} search={false}   rowKey="id"   dataSource = {dealerService}
            columns={columnService} toolbar={{settings:[]}} toolBarRender={()=>[
              <Button type='primary' key='primary' onClick={async() => {
                var val = await findProviderList({current:1,pageSize:100})
                if (val.errorCode === '200') {
                  const current = dealerService.map((item:any)=>item.serviceId)
                  setServices(val.data.filter((item:any)=>{
                    return current.indexOf(item.id)<0
                  }))
                  setShowService(true)
                } else {
                  message.error('获取失败');
                }

              }}>选择</Button>
            ]}>

          </ProTable>
       </Drawer>
       <ModalForm style={{zIndex:100}}
        title="服务商"
        width={1000}
        modalProps={{
          forceRender: true,
            destroyOnClose: true,
        }}
        visible={modalVisible}
        onVisibleChange={(val)=>{
          setModalVisible(val)
        }}
        onFinish={async(value)=>{
          value.serviceLicenseShipId = shipId+"_1"
          value.serviceAccountShipId = shipId+"_2"
          var val = undefined
          if(serviceInfo.id){
            value.id = serviceInfo.id
            val = await editProvider(value)
          }else{
            val = await addProvider(value)
          }
          if(val.errorCode==='200'){
            refershService()
            return true;
          }else{
            message.error("添加失败");
            return false;
          }
        }}
      >
        <ProForm.Group >
          <ProFormText initialValue={serviceInfo.serviceName} name="serviceName" label="服务商名称" rules={[{ required: true}]}    width="md"/>
        </ProForm.Group>
        <ProForm.Group>
          <ProFormText initialValue={serviceInfo.serviceContact}   name="serviceContact" label="联系人" rules={[{ required: true}]}    width="sm"/>
          <ProFormText initialValue={serviceInfo.servicePhone}  name="servicePhone" label="电话" rules={[{ required: true}]}    width="sm"/>
          <ProFormText initialValue={serviceInfo.serviceMail}  name="serviceMail" label="邮箱"   width="sm"/>
        </ProForm.Group>
        <ProForm.Group>
          <ProFormText initialValue={serviceInfo.serviceBankName}  name="serviceBankName" label="收款开户名称" rules={[{ required: true}]}   width="sm"/>
          <ProFormText initialValue={serviceInfo.serviceBank}  name="serviceBank" label="收款开户银行" rules={[{ required: true}]}    width="sm"/>
          <ProFormText initialValue={serviceInfo.serviceBankAccount}  name="serviceBankAccount" label="银行账号" rules={[{ required: true}]}    width="sm"/>
        </ProForm.Group>
        <h4>营业执照附件</h4>
        <Upload
            {...uploadProps} data={{'shipId':shipId+"_1",'userId':sessionStorage.getItem("userId")}} headers={{
              'authorization':`${sessionStorage.getItem('token')}`}} 
            listType="picture-card"
            fileList={fileList1}
            onRemove={(record)=>{
              confirm({
                content: "确定删除吗？",
                onOk:async()=> {
                    var req = request('/xwyl/attachment/deleteAtt', {
                    method: 'POST',
                    requestType:'form',
                    data: {
                      ...{"id":record.uid},
                      method: 'post',
                    },
                  });
                  var val =await req;
                  if(val.errorCode==='200'){
                    var newList=fileList1.filter((item:any)=>{
                      return item.uid!=record.uid;
                    });
                    setFileList1(newList)
                  }else{
                    message.error("删除失败");
                  }
                },
                onCancel() {
                  console.log('Cancel');
                },
              });
            }}
            onChange={(info:any)=>{
              if (info.file.status === 'done') {
                if(info.file.response.errorCode==="200"){
                  message.success(`${info.file.name}上传成功`);
                  var data = info.file.response.data;
                  data.uid = data.attId;
                  data.name = info.file.name;
                  data.url = data.location;
                  data.status ='done';
                  fileList1.push(data);
                  setFileList1([...fileList1])
                }else{
                  message.error(`${info.file.name} 上传失败.`);
                }
              } else if (info.file.status === 'error') {
                message.error(`${info.file.name} 上传失败.`);
              }
            }}
          >
              {uploadButton(fileList1)}
          </Upload>
          <h4>收款账户凭证</h4>
          <Upload
            {...uploadProps} data={{'shipId':shipId+"_2",'userId':sessionStorage.getItem("userId")}} headers={{
              'authorization':`${sessionStorage.getItem('token')}`}} 
            listType="picture-card"
            fileList={fileList2}
            onRemove={(record)=>{
              confirm({
                content: "确定删除吗？",
                onOk:async()=> {
                    var req = request('/xwyl/attachment/deleteAtt', {
                    method: 'POST',
                    requestType:'form',
                    data: {
                      ...{"id":record.uid},
                      method: 'post',
                    },
                  });
                  var val =await req;
                  if(val.errorCode==='200'){
                    var newList=fileList2.filter((item:any)=>{
                      return item.uid!=record.uid;
                    });
                    setFileList2(newList)
                  }else{
                    message.error("删除失败");
                  }
                },
                onCancel() {
                  console.log('Cancel');
                },
              });
            }}
            onChange={(info:any)=>{
              if (info.file.status === 'done') {
                if(info.file.response.errorCode==="200"){
                  message.success(`${info.file.name}上传成功`);
                  var data = info.file.response.data;
                  data.uid = data.attId;
                  data.name = info.file.name;
                  data.url = data.location;
                  data.status ='done';
                  fileList2.push(data);
                  setFileList2([...fileList2])
                }else{
                  message.error(`${info.file.name} 上传失败.`);
                }
              } else if (info.file.status === 'error') {
                message.error(`${info.file.name} 上传失败.`);
              }
            }}
          >
              {uploadButton(fileList2)}
          </Upload>
      </ModalForm>
       <Drawer title='详情' style={{zIndex:99}} width={1200} onClose={()=>setShowService(false)} visible={showService} destroyOnClose={true} forceRender={true}>
          <ProTable pagination={false} search={false}   rowKey="id"   dataSource = {services}
            columns={sColumn} toolbar={{settings:[]}} toolBarRender={()=>[
              <Button type='primary' key='primary' hidden={showDetail} onClick={() => {
                setServiceInfo({})
                setShipId(newUUID())
                setModalVisible(true)
              }}>新增</Button>
            ]}>

          </ProTable>
       </Drawer>
      
  </PageContainer>
  );
};